import React, { useState, useEffect } from "react";
import Tabbar from "@/components/TabBar";
import { SideBar } from "antd-mobile";
import { fetchItems, fetchCates } from "@/api";
import Items from "./components/Items";
import { useNavigate,useDispatch } from "umi";
import "./assets/style.scss";
import SearchInto from "./components/search";
export default function index() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const [activeIndex, setActiveIndex] = useState(0);
  const [cates, setCates] = useState([]);
  // 对应高亮分类商品
  const [items, setItems] = useState([]);
  // 请求所有分类
  const getCates = () => {
    fetchCates().then((res) => {
      if (res.data.code === 0) {
        setCates(res.data.data);
      }
    });
  };
  // 初始化 分类数据赋值后 调用 初始化获取商品
  useEffect(() => {
    if (cates.length) {
      getItems();
    }
  }, [cates, activeIndex]);
  // 获取高亮分类下商品
  const getItems = () => {
    fetchItems({
      categoryId: cates[activeIndex].id,
    }).then((res) => {
      if (res.data.code === 0) {
        setItems(res.data.data.result);
      }
      if (res.data.code === 700) {
        setItems([]);
      }
    });
  };
  useEffect(() => {
    getCates();
  }, []);
  const addCartItem = (id: number) => {
    dispatch({
      type: 'cart/addItem',
      data: {
        goodsId: id,
        number: 1
      }
    })
  }
  return (
    <div>
      <SearchInto/>
      <div className="catePage">
        <div className="container">
          <div className="cate-container">
            <SideBar activeKey={activeIndex} onChange={setActiveIndex}>
              {cates.map((cate, index) => {
                return <SideBar.Item key={index} title={cate.name} />;
              })}
            </SideBar>
          </div>
          <div className="item-container">
            <Items
              items={items}
              clickItems={(id: number) => {
                navigate(`/detail/${id}`);
              }}
              clickCartIcon={ 
                (id: number) => {
                  addCartItem(id)
                }
               }
            />
          </div>
        </div>
        <Tabbar />
      </div>
    </div>
  )
}
